/**
 * jsonp: 前端传一个自定义方法 调后端接口时调用前端自定义的方法
 *
 * */

const http = require("http")
const https = require("https")
const url = require("url");

http.createServer((req, res) => {
  const urlObj = url.parse(req.url, true)
  res.writeHead(200, {
    "Content-Type": "application/json;charset=utf-8",
    // cors 头
    "access-control-allow-origin": "*"
  })
  switch (urlObj.pathname) {
    case "/api/aaa":
     // 客户端去 猫眼要数据
      httppost((data) => {
        res.end(data)
      })
      break;
    default:
      res.end("404")
  }
}).listen(3000)


function httppost(cb) {
  let data = ''
  const options = {
    hostname: "m.xiaomiyoupin.com",
    port: "443", //https 默认的端口号是443， http 默认的端口号是80
    path: "/mtop/market/search/placeHolder",
    method: "POST",
    headers: {
      "Content-type": "application/json"
      // "Content-Type": "x-www-form-urlencoded"
    }

  }
  const req = https.request(options,(res)=> {
    res.on("data", chunk => {
      data+= chunk
    })
    res.on("end", ()=> {
      cb(data)
    })
  })

  // req.write("name=kerwin&age=100")
  req.write(JSON.stringify([{},{"ypClient":3}])) // 里面是入参
  req.end()
}